package com.test.ssh.webapp.action;

import java.util.List;

import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;

import com.opensymphony.xwork2.util.CreateIfNull;
import com.opensymphony.xwork2.util.KeyProperty;
import com.test.ssh.model.User;
import com.test.ssh.service.GenericManager;
import com.test.ssh.service.UserManager;

@Results(
		{
			@Result(name="list",value="user/userList.jsp") ,
			@Result(name="newUser",value="user/userEditForm.jsp") ,
			@Result(name="editUserForm",value="user/userEditForm.jsp"),
			@Result(name="batchEditForm",value="user/userEditList.jsp")
			
		}
		)

public class UserAdminAction {
	
	private Long id ;
	private User user ;
	private UserManager userManager ;
	@KeyProperty(value="id")
	@CreateIfNull( value = true )
	private List<User> users ;
	private List<User> newUsers ;
	
	
	public String batchEditForm(){
		users = userManager.findByHql("from User order by username", null);
		return "batchEditForm";
	}
	public String batchSave(){
		//System.out.println("UserAdminAction.batchSave()"+users == null);
		if(null != users){
		for (User user : users) {
			userManager.save(user);
		}
		}
		for (User user : newUsers) {
			String username = user.getUsername();
			if( username != null && !"".equals(username)){
				userManager.save(user);
			}
		}
		return list();
	}
	public String list() {
		users = userManager.findByHql("from User order by username", null) ;
		return "list" ;
	}
	
	public String newUser() {
		return "newUser" ;
	}
	
	public String editUser() {
		user=userManager.get(id) ;
		return "editUserForm" ;
	}
	
	public String delete() {
		userManager.remove(id);
		return list() ;
	}
	
	public String save() {
		user=userManager.save(user) ;
		return list() ;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	public List<User> getNewUsers() {
		return newUsers;
	}
	public void setNewUsers(List<User> newUsers) {
		this.newUsers = newUsers;
	}

	
	
	
}
